package com.mfp.java.testYou.ui.mvc;

import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.mfp.java.testYou.model.UiSelectPair;

/**
 * To use the list, embed it with jsp:include <br/>
 * <p>
 * Set up the data, using request variables with the names:
 * </p>
 * <ul>
 * <li>ATTR_LIST_DATA (java.util.List of com.mfp.java.testYou.model.UiSelectPair)</li>
 * <li>ATTR_LIST_SIZE (java.lang.Integer)</li>
 * <li>ATTR_LIST_NAME (java.lang.String)</li>
 * </ul>
 */
public class SelectListComponent extends AbstractMVC {

	private static final Logger log = Logger.getLogger(SelectListComponent.class);

	public static final String ATTR_LIST_DATA = "selectCompListContent";
	public static final String ATTR_LIST_SIZE = "selectCompListSize";
	public static final String ATTR_LIST_NAME = "selectCompListName";

	private static final Integer DEF_SIZE = 5;
	private static final String DEF_NAME = "selectList";

	public SelectListComponent(HttpServletRequest request, HttpServletResponse response) {
		super(request, response);
	}

	public List<UiSelectPair> getList() {

		try {
			@SuppressWarnings("unchecked")
			List<UiSelectPair> list = (List<UiSelectPair>) (getRequest().getAttribute(ATTR_LIST_DATA));
			return list;
		} catch (ClassCastException e) {
			log.error("Can't create UI list: " + e.getClass().getName() + " " + e.getMessage());
		} catch (NullPointerException e) {
			log.error("Can't create UI list: " + e.getClass().getName() + " " + e.getMessage());
		}

		// if any problems appear, return an empty list to keep jsp intact.
		return new LinkedList<UiSelectPair>();
	}

	public int getSize() {
		Object size = getRequest().getAttribute(ATTR_LIST_SIZE);
		try {
			Integer sizeInt = (Integer) size;
			return sizeInt;
		} catch (NullPointerException e) {
			log.warn("Size of list not specified, using default: " + DEF_SIZE);
		} catch (ClassCastException e) {
			log.warn("Error casting size of list. (use java.lang.Integer). Using default size: " + DEF_SIZE);
		}
		return DEF_SIZE;
	}

	public String getName() {
		Object name = getRequest().getAttribute(ATTR_LIST_NAME);
		try {
			String nameString = (String) name;
			return nameString;
		} catch (NullPointerException e) {
			log.warn("Name of list was not specified, using default: " + DEF_NAME);
		} catch (ClassCastException e) {
			log.warn("Error casting name of list. (use java.lang.String). Using default: " + DEF_NAME);
		}
		return DEF_NAME;
	}

}
